package com.cloudfun.campusshare.service.handler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.cloudfun.campusshare.common.constant.DelayMsgType;
import com.cloudfun.campusshare.common.constant.DeviceStatus;
import com.cloudfun.campusshare.common.constant.RedisKey;
import com.cloudfun.campusshare.common.model.vo.PumpWorkVO;
import com.cloudfun.campusshare.entity.*;
import com.cloudfun.campusshare.repo.*;
import com.cloudfun.campusshare.sender.DelayMessage;
import com.cloudfun.campusshare.service.DeviceOpServiceDelegate;
import com.cloudfun.campusshare.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class LiquidPumpMessageHandler implements DelayMessageHandler {

    @Autowired
    private OrderEntityRepo orderEntityRepo;

    @Autowired
    private PumpWashRelRepo pumpWashRelRepo;
    @Autowired
    private DeviceModeRepo deviceModeRepo;

    @Autowired
    private DeviceOpServiceDelegate deviceOpServiceDelegate;


    @Autowired
    private LiquidPumpOrderEntityRepo liquidPumpOrderEntityRepo;

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

  /*  @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DeviceService deviceService;

    // 检查加液泵的雨量有没有用完
    private ScheduledExecutorService service = Executors
            .newSingleThreadScheduledExecutor();*/

    @Override
    public DelayMsgType support() {
        return DelayMsgType.LIQUID_PUMP;
    }

    @Override
    public void handleMessage(DelayMessage message) {
        prepareUserContext(message);
        switch (message.getConsumerType()) {
            case START_DEVICE:
                log.info("开始启动液体泵");
                OrderEntity orderEntity;
                DeviceEntity pumpDeviceEntity;
                Optional<OrderEntity> orderEntityOptional = orderEntityRepo.findById(message.getOrderId());
                if (!orderEntityOptional.isPresent()) {
                    log.error("启动液体泵失败,订单id {} 不存在", message.getOrderId());
                    return;
                }
                orderEntity = orderEntityOptional.get();
                // 查询设备关联关系
                PumpWashRel byWashId = pumpWashRelRepo.findByWashImei(orderEntity.getDeviceEntity().getImei());
                if (byWashId == null) {
                    log.error("启动液体泵失败,原因:洗衣机设备imei {} 关联液体泵不存在", orderEntity.getDeviceEntity().getImei());
                    return;
                }
                Optional<DeviceEntity> optionalDeviceEntity = Optional.ofNullable(deviceEntityRepo.findByImei(byWashId.getPumpImei()));
                if (!optionalDeviceEntity.isPresent()) {
                    log.error("启动液体泵失败,原因:液体泵设备imei {} 液体泵不存在", byWashId.getPumpImei());
                    return;
                }
                pumpDeviceEntity = optionalDeviceEntity.get();
                // 判断是否有可用设备指令
                if (orderEntity.getCommand() != null) {
                    LiquidPumpOrderEntity liquidPumpOrderEntity=new LiquidPumpOrderEntity();
                    PumpWorkVO vo = new PumpWorkVO();
                    vo.setDeviceId(byWashId.getPumpImei());
                    String command = orderEntity.getCommand();
                    JSONArray liquidPumpModes = JSONUtil.parseObj(command).getJSONArray("liquidPumpModes");
                    liquidPumpModes.stream().forEach(modeId -> {
                        DeviceModeEntity deviceModeEntity;
                        Optional<DeviceModeEntity> optional = deviceModeRepo.findById(modeId.toString());
                        if (!optional.isPresent()) {
                            return;
                        }
                        deviceModeEntity = optional.get();
                        if (!pumpDeviceEntity.getModeSetId().equals(deviceModeEntity.getModeSetId())){
                            log.error("启动液体泵失败,原因:液体泵设备imei {} 与用户选择模式ModeSetId {} {} 不匹配", byWashId.getPumpImei(),deviceModeEntity.getModeSetId(),pumpDeviceEntity.getModeSetId());
                            return;
                        }
                        if (deviceModeEntity.getMetaModeId().equals("803") || deviceModeEntity.getMetaModeId().equals("804")) {
                            vo.setFirstPumpWorkTime(deviceModeEntity.getDosage() / 10);
                            vo.setFirstPumpDelayTime(0);
                            liquidPumpOrderEntity.setFirstPumpPrice(deviceModeEntity.getPrice());
                            liquidPumpOrderEntity.setFirstPumpDosage(deviceModeEntity.getDosage());
                            vo.setOrderId(orderEntity.getId());
                        } else if (deviceModeEntity.getMetaModeId().equals("805")) {
                            liquidPumpOrderEntity.setSecondPumpDosage(deviceModeEntity.getDosage());
                            liquidPumpOrderEntity.setSecondPumpPrice(deviceModeEntity.getPrice());
                            vo.setSecondPumpWorkTime(deviceModeEntity.getDosage() / 10);
                            vo.setSecondPumpDelayTime(0);
                            vo.setOrderId(orderEntity.getId());
                        }
                    });
                    liquidPumpOrderEntity.setOrderId(orderEntity.getId());
                    liquidPumpOrderEntity.setDeviceId(pumpDeviceEntity.getId());
                    liquidPumpOrderEntityRepo.save(liquidPumpOrderEntity);
                    deviceOpServiceDelegate.pumpStart(vo);
                    // 启动一个定时任务 查看加液泵用量是否用完，用完将加液泵状态更新为PAUSE
                    /*service.schedule(()->{
                        if(stringRedisTemplate.opsForSet().remove(RedisKey.PUMP_PAUSE_IMEI,byWashId.getPumpImei()) > 0){
                            try {
                                deviceService.updateDeviceStatus(DeviceStatus.PAUSE.name(), byWashId.getPumpImei());
                                log.info("{}加液泵用量不足",byWashId.getPumpImei());
                            } catch (Exception e) {
                                log.error("更新加液泵的状态暂停失败{}",e);
                            }
                        }
                    },vo.getFirstPumpWorkTime() + vo.getSecondPumpWorkTime() + 5, TimeUnit.SECONDS);*/
                    log.info("液体泵启动完成");
                } else {
                    log.info("订单id {} 没有启动液体泵指令", orderEntity.getId());
                }
                log.info("液体泵启动结束");
                break;
        }
    }
}
